package com.mes.schedule.manager;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.domain.Operation;
import com.mes.basicdata.domain.Routing;
import com.mes.common.manager.BasicManager;
import com.mes.common.util.IdentityGenerator;
import com.mes.schedule.algorithm.PriorityCalc;
import com.mes.schedule.algorithm.TaskSFCalc;
import com.mes.schedule.dao.DemandSTaskLinkDao;
import com.mes.schedule.domain.DemandSTaskLink;
import com.mes.schedule.domain.SOperationLink;
import com.mes.schedule.domain.SOperationTask;
import com.mes.schedule.domain.SPartTask;
import com.mes.schedule.domain.ScheduleScheme;
import com.mes.schedule.manager.iface.IScheduleDemandManager;
import com.mes.task.dao.DemandDao;
import com.mes.task.domain.Demand;
import com.mes.task.manager.DemandManager;


@Component("scheduleDemandManager")
@Transactional
public class ScheduleDemandManager extends BasicManager implements IScheduleDemandManager{
	 
	protected DemandDao demandDao;
	 
	protected DemandSTaskLinkDao demandSTaskLinkDao;
	 
	protected ScheduleRoutingManager scheduleRoutingManager;
	 
	protected TaskSFCalc taskSFCalc;
	 
	public PriorityCalc priorityCalc;
	 
	protected ScheduleLinkManager scheduleLinkManager;

	 
	protected DemandManager demandManager;

	 
	public void calcDemandPriority(ScheduleScheme scheduleScheme) {
		// TODO Auto-generated method stub
		Page page = null;
		List<Demand> demandList = demandDao.getReceivedDemands(scheduleScheme
				.getDeptUid(), page);
		if (demandList != null && demandList.size() > 0) {
			for (Demand demand : demandList)
				this.calcDemandPriority(demand, scheduleScheme);
		}

	}

	 
	public void calcDemandPriority(Demand demand, ScheduleScheme scheduleScheme) {

		try {
			List<DemandSTaskLink> demandSTaskLinkList = demandSTaskLinkDao
					.getDemandTaskLinksByDemand(
							scheduleScheme.getScheduleUid(), demand
									.getDemandUid(), null);
			if (demandSTaskLinkList != null && demandSTaskLinkList.size() > 0)// 取最紧急任务的优先级
			{
				int minPriority = 999;
				for (DemandSTaskLink demandSTaskLink : demandSTaskLinkList) {
					SPartTask partTask = scheduleScheme.getAllPartTaskMap()
							.get(demandSTaskLink.getPartTaskUid());
					if (partTask != null && partTask.getPriority() != null
							&& partTask.getPriority() < minPriority) {
						minPriority = partTask.getPriority();
					}
				}

//				demand.setPriority((long) minPriority);
			} else {

				// 虚投一个零件任务，取零件任务的优先级
				SPartTask partTask = new SPartTask();
				partTask.setTaskUid(IdentityGenerator.GetIdentityUUID());
//				partTask.setPlanQty(demand.getDueQty());
				partTask.setScheme(scheduleScheme);
				partTask.setLateFinish(demand.getLateFinish());
				Routing routing = this.scheduleRoutingManager
						.getDefaultRouting(demand.getPartUid());

				List<SOperationTask> opTaskList = partTask
						.getOperationTaskList();
				List<Operation> opList = routing.getOperations();

				if (opList != null && opList.size() > 0) {
					for (int i = 0; i < opList.size(); i++) {
						Operation operation = opList.get(i);

						SOperationTask newOpTask = new SOperationTask();
						newOpTask.setOperationId(operation.getOperationId().floatValue());
						if (operation.getEstiPostOpTime() != null)
//							newOpTask.setEstiPreTime(operation
//									.getEstiPostOpTime());
						if (operation.getEstiRunTime() != null)
//							newOpTask
//									.setEstiRunTime(operation.getEstiRunTime());
						newOpTask.setScheme(scheduleScheme);
						newOpTask.setTaskUid(partTask.getTaskUid() + "-" + i);
						newOpTask.setPlanQty(partTask.getPlanQty());
						newOpTask.calTaskWork();
						newOpTask.setParentTask(partTask);
						opTaskList.add(newOpTask);
					}

					// 添加缺省链接关系
					// lqm todo
					// 应该考虑网络
					for (int i = 1; i < opTaskList.size(); i++) {

						SOperationLink link = new SOperationLink();

						SOperationTask predSo = opTaskList.get(i - 1);
						SOperationTask succSo = opTaskList.get(i);

						link.setPredOperationTask(predSo);
						link.setSuccOperationTask(succSo);
						link.setLinkType(SOperationLink.LINKTYPE_FTS);
						link.setLinkLag(0);

						predSo.getSuccLinkSet().add(link);
						succSo.getPredLinkSet().add(link);
					}
				}

				taskSFCalc.calcSF(partTask);
				priorityCalc.calcPartTaskPriority(partTask);

//				demand.setPriority(partTask.getPriority().longValue());

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Transactional
	public void addDemandDelivery(Demand demand) throws Exception {
		Demand originDemand = demandDao.getById(demand.getDemandUid());
		if (originDemand == null)
			return;
		Demand newDemand = (Demand) originDemand.clone();
		if (demand.getDueQty() >= originDemand.getDueQty())
			throw new Exception("分出数量必须小于原指令数量");
		newDemand.setDemandUid(IdentityGenerator.GetIdentityUUID());
		newDemand.setBatchNum(newDemand.getDemandUid());
		newDemand.setDemandId(originDemand.getDemandId() + "分");
		newDemand.setLateFinish(demand.getLateFinish());
		newDemand.setDueQty(demand.getDueQty());
		newDemand.setParentDemandUid(originDemand.getDemandUid());
		newDemand.setNotes("从指令" + originDemand.getDemandId() + "中分出");
		this.demandManager.add(newDemand);

		originDemand.setDueQty(originDemand.getDueQty() - demand.getDueQty());
		this.demandManager.update(originDemand);

	}

	 
	public void cancelDemandDelivery(Demand demand) throws Exception {
		// TODO Auto-generated method stub
		if(demand.getDemandUid()==null || demand.getParentDemandUid()==null)
			throw new Exception("该指令不是一条合法的分期交付指令！");
		
		Demand deliveryDemand= demandDao.getById(demand.getDemandUid());
		
		Demand originDemand = demandDao.getById(demand.getParentDemandUid());
		if (deliveryDemand==null || originDemand == null)
			throw new Exception("该指令不是一条合法的分期交付指令！");
		
		if(deliveryDemand.getDeliveryQty()!=null)
		{
			if(originDemand.getDeliveryQty()==null)
				originDemand.setDeliveryQty(deliveryDemand.getDeliveryQty());
			else {
				originDemand.setDeliveryQty(deliveryDemand.getDeliveryQty()+originDemand.getDeliveryQty());
			}
		}	
		
		//lqm todo
		
		originDemand.setDueQty(originDemand.getDueQty()+deliveryDemand.getDueQty());
		
		this.update(originDemand);

		this.demandManager.delete(deliveryDemand);

	}
	
	
	 
	public void saveDeamnd(List<Demand> demandlList)
			throws Exception {
		for (Demand demand : demandlList) {
			this.saveDeamnd(demand);
			this.addDemand(demand);
		}

	}
	/**
	 * added by hba to save the added records
	 * @param demand
	 * @throws Exception
	 */
	public void addDemand(Demand demand) throws Exception
	{
//		demand.setDemandState(1l);
		this.demandManager.add(demand);
		
	}

	 
	public void saveDeamnd(Demand demand) throws Exception {
		// TODO Auto-generated method stub
		demand.setIsCritical(demand.getIsCritical());
		this.demandManager.update(demand);
		
		

	}
	
	//2015-09-18 采用IBasicManager的update   不采用 AbstractManagerSupport  否则basicDao为null
//	public void setIDemandDao(IDemandDao demandDao) {
//		this.demandDao = demandDao;
//		/*
//		 * 一定注意加上这句话
//		 */
//		super.setBasicDao(demandDao);
//	}
	
}
